class NaiveBayes:
   def fit(self, X, y):
       self.classes = np.unique(y)
       self.class_probabilities = np.zeros(len(self.classes))
       self.mean = np.zeros((len(self.classes), X.shape[1]))
       self.var = np.zeros((len(self.classes), X.shape[1]))
       for idx, c in enumerate(self.classes):
           X_c = X[y == c]
           self.class_probabilities[idx] = X_c.shape[0] / X.shape[0]
           self.mean[idx, :] = np.mean(X_c, axis=0)
           self.var[idx, :] = np.var(X_c, axis=0)

   def _pdf(self, x, mean, var):
       exponent = np.exp(-((x - mean) ** 2) / (2 * var))
       return exponent / (np.sqrt(2 * np.pi * var))

   def predict(self, X):
       posteriors = []
       for x in X:
           likelihoods = [np.prod(self._pdf(x, self.mean[i], self.var[i])) for i in range(len(self.classes))]
           posterior = [self.class_probabilities[i] * likelihoods[i] for i in range(len(self.classes))]
           posteriors.append(posterior)
       return np.argmax(posteriors, axis=1)

# 加载数据
def load_iris_from_csv(file_path):
   data = []
   label_map = {'Iris-setosa': 0, 'Iris-versicolor': 1, 'Iris-virginica': 2}
   with open(file_path, 'r') as file:
       reader = csv.reader(file)
       next(reader)  # 跳过第一行
       for row in reader:
           row[-1] = label_map[row[-1]]  # 将类别数据转换为数值标签
           data.append([float(x) for x in row])
   data = np.array(data, dtype=float)
   X = data[:, :-1]  # 特征
   y = data[:, -1]  # 目标变量
   return X, y


# 读取iris数据集
X, y = load_iris_from_csv('iris_data.csv')

# 划分数据集
np.random.seed(0)  # 设置随机数种子，以确保结果的可重现性
indices = np.random.permutation(len(X))
X = X[indices]
y = y[indices]
split_idx = int(0.8 * len(X))
X_train, X_test = X[:split_idx], X[split_idx:]
y_train, y_test = y[:split_idx], y[split_idx:]

# 训练朴素贝叶斯分类器
nb = NaiveBayes()
nb.fit(X_train, y_train)

# 进行预测
y_pred = nb.predict(X_test)

# 计算准确率
correct_predictions = np.sum(y_pred == y_test)
accuracy = correct_predictions / len(y_test)
print("准确率：", accuracy）